package com.example.redis_canal_mysql_demo.hyperLogService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author LiHaoyang
 * @date 2023/4/26  18:43
 **/
@Service
@Slf4j
public class HyperLogLogService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 模拟ip提交
     */
    @PostConstruct
    public void init(){
        new Thread(()->{
            String ip = null;
            for (int i=0;i<200;i++){
                Random random = new Random();
                ip = random.nextInt(256)+"."+
                        random.nextInt(256)+"."+
                        random.nextInt(256)+"."+
                        random.nextInt(256);
                Long hll = redisTemplate.opsForHyperLogLog().add("hll", ip);
                log.info("当前ip位{},该ip访问次数为{}",ip,hll);

                // 暂停三秒
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();
    }

    public long uv(){
        return redisTemplate.opsForHyperLogLog().size("hll");
    }

}
